package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Product;
import model.User;
import model.YourCart;

import dto.DataManager;

/**
 * Servlet implementation class UpdateCart
 */
@WebServlet("/UpdateCart")
public class UpdateCart extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
		String action = request.getParameter("action");

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		DataManager dataManager = new DataManager();
		User user = dataManager.getUserWithUserName(username);
		PrintWriter out = response.getWriter();
		if (action.equals("deleteItem")) {
			int youcartId = Integer
					.parseInt(request.getParameter("yourCartId"));
			dataManager.deleteYourCartItem(youcartId);
			int tongtien = 0;
			List<YourCart> ys = dataManager
					.getAllCartByUserId(user.getUserId());
			for (YourCart y : ys) {
				Product p = dataManager.getProductById(y.getProductId());
				tongtien += y.getNumber() * (p.getPrice());

			}
			out.print(tongtien);

		} else if (action.equals("updateNumber")) {
			int youcartId = Integer
					.parseInt(request.getParameter("yourCartId"));
			String number = request.getParameter("number");
			// int number = Integer.parseInt(request.getParameter("number"));
			dataManager.updateYourCart(youcartId, Integer.parseInt(number));
			int tongtien = 0;
			List<YourCart> ys = dataManager
					.getAllCartByUserId(user.getUserId());
			for (YourCart y : ys) {
				Product p = dataManager.getProductById(y.getProductId());
				tongtien += y.getNumber() * (p.getPrice());
			}
			out.print(tongtien);

		} else if (action.equals("thanhtoan")) {
			response.sendRedirect("payment.jsp");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
